<template>
    <div class="teacher-attendance-manage">
        <div class="breadcrumb">
            <span>考勤管理</span> &gt; <span>教师考勤</span> &gt; <span>我的请假</span>
        </div>

        <div class="tabs">
            <div class="tab-item active">我的请假</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/approval')">请假审批</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/statistics')">考勤统计</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/time-setting')">考勤时间设置</div>
        </div>

        <div class="filter-bar">
            <el-date-picker v-model="applyTime" type="date" placeholder="申请时间"
                style="width: 150px; margin-right: 10px;" />
            <el-date-picker v-model="leaveTime" type="date" placeholder="请假时间"
                style="width: 150px; margin-right: 10px;" />
            <el-select v-model="leaveType" placeholder="请假类型" style="width: 120px; margin-right: 10px;">
                <el-option label="事假" value="事假" />
                <el-option label="病假" value="病假" />
                <el-option label="公假" value="公假" />
            </el-select>
            <el-select v-model="approvalStatus" placeholder="审批状态" style="width: 120px; margin-right: 10px;">
                <el-option label="待审批" value="待审批" />
                <el-option label="审批通过" value="审批通过" />
                <el-option label="审批驳回" value="审批驳回" />
            </el-select>
            <el-button type="primary" @click="handleSearch">查 询</el-button>
            <el-button style="margin-left: 8px;" @click="handleReset">重 置</el-button>
            <el-button type="primary" style="margin-left: auto;" @click="handleApplyLeave">
                <el-icon>
                    <Plus />
                </el-icon> 申请请假
            </el-button>
        </div>

        <div class="result-info">查询结果：共计 {{ leaveData.length }} 条数据</div>

        <el-table :data="leaveData" border style="width: 100%;" v-loading="loading">
            <el-table-column prop="department" label="部门" min-width="100" />
            <el-table-column prop="teacherName" label="姓名" min-width="100" />
            <el-table-column prop="startTime" label="开始时间" min-width="150" />
            <el-table-column prop="endTime" label="结束时间" min-width="150" />
            <el-table-column prop="reason" label="请假原因" min-width="120">
                <template #default="scope">
                    <el-link type="primary" @click="viewReason(scope.row)">查看</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="leaveType" label="请假类型" min-width="100" />
            <el-table-column prop="applyTime" label="申请时间" min-width="150" />
            <el-table-column prop="status" label="审批状态" min-width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '审批通过' ? 'success' :
                        scope.row.status === '审批驳回' ? 'danger' : 'warning'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                    <el-link v-if="scope.row.status === '待审批'" type="primary" @click="editLeave(scope.row)"
                        style="margin-right: 10px;">
                        编辑
                    </el-link>
                    <el-link v-if="scope.row.status === '待审批'" type="danger" @click="cancelLeave(scope.row)">
                        撤销
                    </el-link>
                    <el-link v-else type="primary" @click="viewLeaveDetail(scope.row)">查看详情</el-link>
                </template>
            </el-table-column>
        </el-table>

        <!-- 查看请假原因弹窗 -->
        <el-dialog v-model="reasonDialogVisible" title="请假原因" width="500px">
            <p>{{ currentReasonDetail }}</p>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="reasonDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 查看请假详情弹窗 -->
        <el-dialog v-model="leaveDetailVisible" title="请假详情" width="600px">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="部门">{{ currentLeaveDetail.department }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ currentLeaveDetail.teacherName }}</el-descriptions-item>
                <el-descriptions-item label="请假类型">{{ currentLeaveDetail.leaveType }}</el-descriptions-item>
                <el-descriptions-item label="开始时间">{{ currentLeaveDetail.startTime }}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{ currentLeaveDetail.endTime }}</el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ currentLeaveDetail.applyTime }}</el-descriptions-item>
                <el-descriptions-item label="审批状态">
                    <el-tag :type="currentLeaveDetail.status === '审批通过' ? 'success' :
                        currentLeaveDetail.status === '审批驳回' ? 'danger' : 'warning'">
                        {{ currentLeaveDetail.status }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="请假原因">{{ currentLeaveDetail.reason }}</el-descriptions-item>
                <el-descriptions-item v-if="currentLeaveDetail.approver" label="审批人">
                    {{ currentLeaveDetail.approver }}
                </el-descriptions-item>
                <el-descriptions-item v-if="currentLeaveDetail.approvalTime" label="审批时间">
                    {{ currentLeaveDetail.approvalTime }}
                </el-descriptions-item>
                <el-descriptions-item v-if="currentLeaveDetail.rejectReason" label="驳回理由">
                    {{ currentLeaveDetail.rejectReason }}
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="leaveDetailVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 申请请假弹窗 -->
        <el-dialog v-model="leaveDialogVisible" :title="editingLeave ? '编辑请假' : '申请请假'" width="600px">
            <el-form :model="leaveForm" label-width="100px" ref="leaveFormRef" :rules="leaveRules">
                <el-form-item label="部门" prop="department">
                    <el-select v-model="leaveForm.department" placeholder="请选择部门" style="width: 100%;">
                        <el-option v-for="dept in departmentList" :key="dept.id" :label="dept.departmentName"
                            :value="dept.departmentName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="teacherName">
                    <el-input v-model="leaveForm.teacherName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="请假类型" prop="type">
                    <el-select v-model="leaveForm.type" placeholder="请选择请假类型" style="width: 100%;">
                        <el-option label="事假" value="事假" />
                        <el-option label="病假" value="病假" />
                        <el-option label="公假" value="公假" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker v-model="leaveForm.startTime" type="datetime" placeholder="选择开始时间"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker v-model="leaveForm.endTime" type="datetime" placeholder="选择结束时间"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="请假原因" prop="reason">
                    <el-input v-model="leaveForm.reason" type="textarea" :rows="3" placeholder="请输入请假原因" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="leaveDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitLeaveApplication" :loading="submitting">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getTeacherLeaveList, submitTeacherLeave, cancelTeacherLeave, getDepartmentList } from '@/api/teacherKaoqin'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)

// 当前用户信息（实际项目中应从用户登录信息获取）
const currentUser = {
    teacherId: 'T001',
    teacherName: '张老师',
    department: '语文组'
}

// 我的请假相关数据
const applyTime = ref()
const leaveTime = ref()
const leaveType = ref('')
const approvalStatus = ref('')
const leaveData = ref<any[]>([])

// 请假详情查看
const leaveDetailVisible = ref(false)
const currentLeaveDetail = ref<Record<string, any>>({})

// 请假原因查看
const reasonDialogVisible = ref(false)
const currentReasonDetail = ref('')

// 部门列表
const departmentList = ref<any[]>([])

// 申请请假相关
const leaveFormRef = ref<FormInstance>()
const leaveDialogVisible = ref(false)
const editingLeave = ref(false)
const currentLeaveId = ref('')
const leaveForm = ref({
    type: '事假',
    department: '',
    teacherName: '',
    startTime: '',
    endTime: '',
    reason: ''
})

// 表单验证规则
const leaveRules = {
    type: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
    department: [{ required: true, message: '请选择部门', trigger: 'change' }],
    teacherName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    reason: [{ required: true, message: '请填写请假原因', trigger: 'blur' }]
}

// 日期格式化工具函数
function formatDate(date: Date | string): string {
    if (!date) return ''
    if (typeof date === 'string') {
        return date
    }

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 查询请假数据
async function handleSearch() {
    loading.value = true
    try {
        const params: any = {
            teacherId: currentUser.teacherId // 获取当前登录用户的请假记录
        }

        if (leaveType.value) {
            params.leaveType = leaveType.value
        }

        if (approvalStatus.value) {
            params.status = approvalStatus.value
        }

        if (applyTime.value) {
            params.applyDate = formatDate(applyTime.value).split(' ')[0]
        }

        if (leaveTime.value) {
            params.leaveDate = formatDate(leaveTime.value).split(' ')[0]
        }

        const response: any = await getTeacherLeaveList(params)
        if (response.data && response.data.code === 200) {
            leaveData.value = response.data.data
        }
    } catch (error) {
        console.error('获取请假数据失败:', error)
        ElMessage.error('获取请假数据失败')
    } finally {
        loading.value = false
    }
}

// 重置筛选条件
function handleReset() {
    applyTime.value = undefined
    leaveTime.value = undefined
    leaveType.value = ''
    approvalStatus.value = ''
    handleSearch()
}

// 查看请假原因
function viewReason(row: any) {
    currentReasonDetail.value = row.reason || '无详细原因'
    reasonDialogVisible.value = true
}

// 查看请假详情
function viewLeaveDetail(row: any) {
    currentLeaveDetail.value = { ...row }
    leaveDetailVisible.value = true
}

// 获取部门列表
async function fetchDepartmentList() {
    try {
        const response: any = await getDepartmentList()
        if (response.data && response.data.code === 200) {
            departmentList.value = response.data.data
        }
    } catch (error) {
        console.error('获取部门列表失败:', error)
    }
}

// 申请请假
function handleApplyLeave() {
    editingLeave.value = false
    leaveForm.value = {
        type: '事假',
        department: currentUser.department, // 默认填充当前用户部门，但可以修改
        teacherName: currentUser.teacherName, // 默认填充当前用户姓名，但可以修改
        startTime: '',
        endTime: '',
        reason: ''
    }
    leaveDialogVisible.value = true
}

// 编辑请假
function editLeave(row: any) {
    editingLeave.value = true
    currentLeaveId.value = row.id
    leaveForm.value = {
        type: row.leaveType,
        department: row.department,
        teacherName: row.teacherName || row.name, // 兼容两种字段名
        startTime: row.startTime,
        endTime: row.endTime,
        reason: row.reason
    }
    leaveDialogVisible.value = true
}

// 撤销请假
function cancelLeave(row: any) {
    ElMessageBox.confirm('确定要撤销此请假申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        submitting.value = true
        try {
            const response: any = await cancelTeacherLeave(row.id)
            if (response.data && response.data.code === 200) {
                ElMessage.success(response.data.message || '请假申请已撤销')
                handleSearch() // 刷新数据
            } else {
                ElMessage.error(response.data?.message || '撤销失败')
            }
        } catch (error) {
            console.error('撤销请假失败:', error)
            ElMessage.error('撤销请假失败')
        } finally {
            submitting.value = false
        }
    }).catch(() => { })
}

// 提交请假申请
function submitLeaveApplication() {
    leaveFormRef.value?.validate(async (valid) => {
        if (!valid) return

        if (!leaveForm.value.startTime || !leaveForm.value.endTime) {
            ElMessage.warning('请选择开始和结束时间')
            return
        }

        const startTime = new Date(leaveForm.value.startTime).getTime()
        const endTime = new Date(leaveForm.value.endTime).getTime()
        if (startTime >= endTime) {
            ElMessage.warning('结束时间必须晚于开始时间')
            return
        }

        submitting.value = true
        try {
            if (editingLeave.value) {
                // 编辑现有请假申请
                // 实际应调用API，这里简化处理
                const index = leaveData.value.findIndex(item => item.id === currentLeaveId.value)
                if (index !== -1) {
                    leaveData.value[index].department = leaveForm.value.department;
                    leaveData.value[index].teacherName = leaveForm.value.teacherName;
                    leaveData.value[index].leaveType = leaveForm.value.type;
                    leaveData.value[index].startTime = formatDate(leaveForm.value.startTime);
                    leaveData.value[index].endTime = formatDate(leaveForm.value.endTime);
                    leaveData.value[index].reason = leaveForm.value.reason;
                    leaveData.value = [...leaveData.value];
                }
                ElMessage.success('请假申请修改成功')
            } else {
                // 提交新的请假申请
                const leaveData = {
                    teacherId: currentUser.teacherId,
                    teacherName: leaveForm.value.teacherName,
                    department: leaveForm.value.department,
                    leaveType: leaveForm.value.type,
                    startTime: formatDate(leaveForm.value.startTime),
                    endTime: formatDate(leaveForm.value.endTime),
                    reason: leaveForm.value.reason,
                    applyTime: formatDate(new Date())
                }

                const response: any = await submitTeacherLeave(leaveData)
                if (response.data && response.data.code === 200) {
                    ElMessage.success(response.data.message || '请假申请提交成功')
                    handleSearch() // 刷新数据
                } else {
                    ElMessage.error(response.data?.message || '提交失败')
                }
            }
            leaveDialogVisible.value = false
        } catch (error) {
            console.error('提交请假申请失败:', error)
            ElMessage.error('提交请假申请失败')
        } finally {
            submitting.value = false
        }
    })
}

// 导航到指定路由
function navigateTo(route: string) {
    router.push(route)
}

// 组件挂载时获取数据
onMounted(() => {
    handleSearch()
    fetchDepartmentList()
})
</script>

<style scoped>
.teacher-attendance-manage {
    padding: 0 20px;
}

.breadcrumb {
    display: flex;
    align-items: center;
    height: 50px;
    font-size: 14px;
    color: #606266;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 20px;
}

.tab-item {
    padding: 12px 20px;
    font-size: 14px;
    cursor: pointer;
    color: #606266;
    border-bottom: 2px solid transparent;
}

.tab-item.active {
    color: #409EFF;
    border-bottom: 2px solid #409EFF;
}

.filter-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;
}

.result-info {
    background-color: #ecf8ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    color: #409EFF;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}
</style>